package com.hui.auth.config.shiro.filter;

import com.hui.auth.dto.JsonResult;
import com.hui.auth.exception.AuthError;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 登录拦截器，用于自定义返回
 * Created by LiaoYunHui on 2017/9/29/029.
 */
public class LoginFilter extends FormAuthenticationFilter {
    /**
     * 没有登录的处理
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        String method = ((ShiroHttpServletRequest) request).getMethod();
        if ("OPTIONS".equals(method)) return true;
        if (this.isLoginRequest(request, response)) {

//            if (this.isLoginSubmission(request, response)) {//使用seiro自带的FormAuth策略
//                return this.executeLogin(request, response);
//            } else {
//                return true;
//            }
            return true;
        } else {
            JsonResult jsonResult = new JsonResult();
            jsonResult.setCode(AuthError.NOT_LOGIN.code);
            jsonResult.setMsg(AuthError.NOT_LOGIN.msg);
            HttpServletRequest httpRequest = ((HttpServletRequest) request);
            HttpServletResponse httpResponse = ((HttpServletResponse) response);
            CrosUtil.crosOrgin(httpRequest, httpResponse);
            httpResponse.getWriter().write(jsonResult.toString());
            return false;
        }
    }

//    /**
//     * 成功之后的处理
//     */
//    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
//        JsonResult jsonResult = new JsonResult();
//        ExcelUser user = (ExcelUser) SecurityUtils.getSubject().getPrincipal();
//        user.setLastLogin(DateUtil.parseDateToString(new Date()));
////        authUserDao.update(user);
////        jsonResult.setData(user);
//        jsonResult.setMsg("登录成功");
//        HttpServletRequest httpRequest = ((HttpServletRequest) request);
//        HttpServletResponse httpResponse = ((HttpServletResponse) response);
//        CrosUtil.crosOrgin(httpRequest, httpResponse);
//        httpResponse.getWriter().write(jsonResult.toString());
//        return true;
//    }
}
